package com.cdn.nodes.netty.server;

import com.cdn.nodes.netty.handler.ServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class NettyServer {
    @Resource
    private ServerHandler serverHandler;
    private final int port = 25238;

    public void start(){
        EventLoopGroup bossGroup = new NioEventLoopGroup(1); // 处理连接请求
        EventLoopGroup workerGroup = new NioEventLoopGroup();  // 处理网络 I/O 操作

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup) // 设置 bossGroup 和 workerGroup
                    .channel(NioServerSocketChannel.class)  // 使用 NIO 传输模式
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            // 添加处理器
                            ch.pipeline().addLast(new StringDecoder());  // 解码器
                            ch.pipeline().addLast(new StringEncoder());  // 编码器
                            ch.pipeline().addLast(serverHandler);  // 自定义的业务逻辑处理器
                        }
                    });

            // 绑定端口并启动服务
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            System.out.println("Netty server started on port " + port);

            // 等待直到服务端关闭
            channelFuture.channel().closeFuture().sync();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
